﻿/// <reference path="application.js" />

function Scene(name) {

    // Name of the scene: used to recover the folder in which the scene is
    this.name = name;
    
    // Invoked when the scene is ready
    this.onload = null;
    this.sceneImageLoaded = false;

    // sceneImage elements
    this.sceneImageSource = null;
    this.sceneImage = null;
    this.sceneCanvas = null;
    this.sceneCanvas2dContext = null;
    this.sceneImageData = null;
    
    if (typeof Scene.initialized == "undefined") {

        /// Initialize the scene
        Scene.prototype.Initialize = function () {
            this.sceneImageSource = app.context.rootUrl + "/scenes/" + name + "/scene.png";
            this.sceneImage = new Image();
            this.sceneImage.onload = function () { this.sceneImageLoaded = true; this.TryFinalizeInitialization(); }.bind(this);
            this.sceneImage.src = this.sceneImageSource;
        };

        /// Check whether the scene is ready to use
        Scene.prototype.TryFinalizeInitialization = function () {
            
            // Check whether all loaded flags are set to true
            if (this.sceneImageLoaded) {

                // Finish initializing the scene
                this.sceneCanvas = document.createElement('canvas');
                this.sceneCanvas2dContext = this.sceneCanvas.getContext('2d');
                this.sceneCanvas.width = this.sceneImage.naturalWidth;
                this.sceneCanvas.height = this.sceneImage.naturalHeight;
                this.sceneCanvas2dContext.drawImage(this.sceneImage, 0, 0);
                this.sceneImageData = this.sceneCanvas2dContext.getImageData(0, 0, this.sceneCanvas.width, this.sceneCanvas.height);

                // Fire onload event
                this.onload();
            }
        };

        /// Draw method
        Scene.prototype.Draw = function () {
            app.context.container2d.drawImage(this.sceneImage,
                app.UI.ToScreenX(0),
                app.UI.ToScreenY(this.sceneImage.naturalHeight));
        };

        /// Think method
        Scene.prototype.Think = function () {

        };

        /// Determines whether x y corrdinate in world reference is in collision with the map
        Scene.prototype.isInCollision = function (x, y) {
            return this.sceneImageData.data[(x + (this.sceneCanvas.height - y) * this.sceneImageData.width) * 4 + 3];
        };

        Scene.initialized = true;
    }
}